<?php

require_once __DIR__ . '/ControllerACL.php';

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ControllerAbstract
 *
 * @author david
 */
abstract class ControllerAbstract {

    protected $useLayout = true;
    protected $config = null;
    public $urlAbsolute = null;

    abstract public function principal();

    public function __construct($config) {
        $this->config = $config;

        //Ajax nao usa layout
        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
            $this->useLayout = false;
        }
    }

    public function renderMenu() {
        include __DIR__ . '/views/layout/menu.php';
    }

    public function renderLayoutScripts() {
        $html = '';
        try {
            if ($this->config && isset($this->config['layout'])) {
                //CSS da config
                if (isset($this->config['layout']['css']) && !empty($this->config['layout']['css'])) {
                    foreach ($this->config['layout']['css'] as $css) {
                        $html .= "<link rel='stylesheet' type='text/css' href='" . $css . "'>" . "\n";
                    }
                }

                //js da config
                if (isset($this->config['layout']['js']) && !empty($this->config['layout']['js'])) {
                    foreach ($this->config['layout']['js'] as $js) {
                        $html .= "<script src='" . $js . "' type='text/javascript'></script>" . "\n";
                    }
                }
            }
        } catch (Exception $exc) {
            
        }
        return $html;
    }

    /**
     * Renderiza a view
     * 
     * @param string $viewName O nome da view a ser renderizada
     * @param array|object $data
     */
    public function render($viewName, $data = null) {
        ob_start();

        $this->controllerACL = new ControllerACL($this->config);
        
        // carrega a view para colocar na variavel content
        include __DIR__ . '/views/' . $viewName . '.php';

        $content = ob_get_clean();

        if ($this->useLayout) {
            include __DIR__ . '/views/layout.php';
        } else {
            echo $content;
        }

        die();
    }

    public function renderView($viewName) {
        include __DIR__ . '/views/' . $viewName . '.php';
    }

    public function renderJson($data) {
        echo json_encode($data);
    }

}